package com.aaa.zs.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * fileName:IllegalCharFilter
 * description:不允许含有任何非法字符参数的访问
 * author: Mr.Ge
 * createTime:2020/11/20 11:11
 * version:1.0.0
 */
@Component
public class IllegalCharFilter extends ZuulFilter {

    @Value("${illegalChar}")
    private String illegalChar;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("进入了非法字符过滤器！");
        //使用zuul中RequestContext提供获取上下文对象方法获取上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取HttpServletRequest
        HttpServletRequest request = currentContext.getRequest();
        //获取HttpServletResponse
        HttpServletResponse response = currentContext.getResponse();
        //获取所有请求的参数名称集合
        //http://192.168.31.117:9999/api/os/order/selectOne?id=1&a=1&b=2&cc=33
        //getParameterNames = [id,a,b,cc...]
        Enumeration<String> parameterNames = request.getParameterNames();
        //获取非法字符 并转换为数组
        String[] illegalCharArray = illegalChar.split(",");
        //循环
        while(parameterNames.hasMoreElements()){
            //第一次循环id 第二次 a 第三次 b
            String parameterName = parameterNames.nextElement();
            //获取该名称的值
            String parameterValue = request.getParameter(parameterName);
            for (String ic : illegalCharArray) {
                if(parameterValue.toLowerCase().contains(ic)){
                    currentContext.setSendZuulResponse(false);
                    //防止响应中文乱码
                    response.setCharacterEncoding("utf-8");
                    try {
                        response.sendError(HttpStatus.SC_FORBIDDEN,"你请求资源的参数中含有非法字符！");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            }
        }
        return null;
    }
}
